package com.crt.nexus.oauth.service;

import com.crt.nexus.security.authentication.UserDetail;
import com.google.common.collect.Lists;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Collection;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserAuthorizationService {

    //    private final UserDao userDao;
    private final PasswordEncoder encoder;

    public void authenticationChecks(UserDetails user, String presentedPassword) {
        if (!encoder.matches(presentedPassword, user.getPassword())) {
            throw new BadCredentialsException("无效的用户名或密码");
        }
    }

    public UserDetail getUserDetail(String username) {
//        return adminDao.find(username).map(admin -> {
        UserDetail detail = new UserDetail();
//            detail.setId(admin.getId());
//            detail.setUsername(admin.getUsername());
//            detail.setPassword(admin.getPassword());
//            detail.setRole(admin.getRole());
//            detail.setState(admin.getState());
        detail.setId(1);
        detail.setUsername("roger");
        detail.setPassword("{bcrypt}$2a$10$aTsEVdv42CHLxsUhPfMmk.kqRZtYSB.Y27O6k9WWcsNKE2gMhjTyW");
        detail.setEnable(true);
        Collection<SimpleGrantedAuthority> authorities = Lists.newArrayList();
        authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
        detail.setAuthorities(authorities);
        if (!detail.isAccountNonLocked()) {
            log.debug("account is locked: {}", detail.isAccountNonLocked());
            throw new LockedException("帐号已锁定");
        }
        if (!detail.isEnabled()) {
            log.debug("account is disabled: {}", detail.isEnabled());
            throw new DisabledException("帐号已禁用");
        }
        if (!detail.isAccountNonExpired()) {
            log.debug("account is expired: {}", detail.isAccountNonExpired());
            throw new AccountExpiredException("帐号已过期");
        }
        return detail;
//        }).orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
    }

}
